package com.learn.core.controller.manager;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.Log;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.BusinessType;
import com.learn.common.enums.OperatorType;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.JwtUtil;
import com.learn.common.utils.PageResult;
import com.learn.common.utils.ResultUtil;
import com.learn.common.utils.StringUtils;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.*;
import com.learn.core.dto.LCourseDTO;
import com.learn.core.service.*;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @auther CodeGenerator
 * @create 2021-03-13 19:41:09
 * @describe 课程表前端控制器
 */
@Api("课程表")
@RestController
@RequestMapping("/manager/course")
public class LCourseController extends WebController<LCourse> {
    @Autowired
    private ILCourseService iLCourseService;
    @Autowired
    private ILOrganizationService ilOrganizationService;
    @Autowired
    private ILCourseSortService ilCourseSortService;
    @Autowired
    private ILThemeService ilThemeService;
    @Autowired
    private ILTeacherService ilTeacherService;
    @Autowired
    private ILCourseTargetService ilCourseTargetService;

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //列表
    @ApiOperation(value = "获取列表全部课程")
    @UserLoginToken
    @PostMapping("/listall")
    public PageResult<LCourse> listAll(@RequestBody LCourseDTO lCourseDTO){
        try {
            if(lCourseDTO==null||lCourseDTO.getPage()==null||lCourseDTO.getRows()==null){
                return new PageResult<LCourse>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lCourseDTO.getPage(),lCourseDTO.getRows());
            QueryWrapper<LCourse> queryWrapper = new QueryWrapper<LCourse>();
            if(lCourseDTO.getCourseType()!=null)
                queryWrapper.eq("course_type",lCourseDTO.getCourseType());
            if(StringUtils.isNotEmpty(lCourseDTO.getCourseSortId()))
                queryWrapper.eq("course_sort_id",lCourseDTO.getCourseSortId());
            if(StringUtils.isNotEmpty(lCourseDTO.getRecommendStutes()))
                queryWrapper.eq("recommend_stutes",lCourseDTO.getRecommendStutes());
            if(StringUtils.isNotEmpty(lCourseDTO.getReleaseStutes()))
                queryWrapper.eq("release_stutes",lCourseDTO.getReleaseStutes());

            if(lCourseDTO.getSortType()!=null&&lCourseDTO.getSortBy()!=null)
                queryWrapper.orderBy(true,lCourseDTO.getSortType(),lCourseDTO.getSortBy());
            Page<LCourse> lCourses = (Page<LCourse>) iLCourseService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lCourses)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            for (LCourse lCours: lCourses) {
                LOrganization lOrganization = ilOrganizationService.getById(lCours.getCourseCompany());
                if(null != lOrganization)
                    lCours.setCourseCompanyName(lOrganization.getOrganizationName());
                LCourseSort lCourseSort = ilCourseSortService.getById(lCours.getCourseSortId());
                if(null != lCourseSort)
                    lCours.setCourseSortName(lCourseSort.getCourseSortName());
                LTheme lTheme = ilThemeService.getById(lCours.getCourseTheme());
                if(null != lTheme)
                    lCours.setCourseThemeName(lTheme.getThemeName());
                LTeacher lTeacher = ilTeacherService.getById(lCours.getTeacher());
                if(null != lTeacher)
                    lCours.setTeacherName(lTeacher.getTeacherName());
                QueryWrapper<LCourseTarget> targetQueryWrapper = new QueryWrapper<LCourseTarget>();
                targetQueryWrapper.eq("course_id",lCours.getCourseId());
                LCourseTarget lCourseTarget = ilCourseTargetService.getOne(targetQueryWrapper);
                if(null != lCourseTarget)
                    lCours.setlCourseTarget(lCourseTarget);
            }
            // 返回
            return new PageResult(lCourses.getTotal(), lCourses, ResultEnum.SUCCESS);
        }catch (Exception e){
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }
    //列表
    @ApiOperation(value = "获取列表--有效课程")
    @UserLoginToken
    @PostMapping("/list")
    public PageResult<LCourse> list(@RequestBody LCourseDTO lCourseDTO){
        try {
            if(lCourseDTO==null||lCourseDTO.getPage()==null||lCourseDTO.getRows()==null){
                return new PageResult<LCourse>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lCourseDTO.getPage(),lCourseDTO.getRows());
            QueryWrapper<LCourse> queryWrapper = new QueryWrapper<LCourse>();
            if(lCourseDTO.getCourseType()!=null)
                queryWrapper.eq("course_type",lCourseDTO.getCourseType());
            if(StringUtils.isNotEmpty(lCourseDTO.getCourseSortId()))
                queryWrapper.eq("course_sort_id",lCourseDTO.getCourseSortId());
            if(StringUtils.isNotEmpty(lCourseDTO.getRecommendStutes()))
                queryWrapper.eq("recommend_stutes",lCourseDTO.getRecommendStutes());
            if(StringUtils.isNotEmpty(lCourseDTO.getReleaseStutes()))
                queryWrapper.eq("release_stutes",lCourseDTO.getReleaseStutes());
            queryWrapper.ge("course_fail_time",formatter.format(new Date()));
            if(lCourseDTO.getSortType()!=null&&lCourseDTO.getSortBy()!=null)
                queryWrapper.orderBy(true,lCourseDTO.getSortType(),lCourseDTO.getSortBy());
            Page<LCourse> lCourses = (Page<LCourse>) iLCourseService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lCourses)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            for (LCourse lCours: lCourses) {
                LOrganization lOrganization = ilOrganizationService.getById(lCours.getCourseCompany());
                if(null != lOrganization)
                    lCours.setCourseCompanyName(lOrganization.getOrganizationName());
                LCourseSort lCourseSort = ilCourseSortService.getById(lCours.getCourseSortId());
                if(null != lCourseSort)
                    lCours.setCourseSortName(lCourseSort.getCourseSortName());
                LTheme lTheme = ilThemeService.getById(lCours.getCourseTheme());
                if(null != lTheme)
                    lCours.setCourseThemeName(lTheme.getThemeName());
                LTeacher lTeacher = ilTeacherService.getById(lCours.getTeacher());
                if(null != lTeacher)
                    lCours.setTeacherName(lTeacher.getTeacherName());
                QueryWrapper<LCourseTarget> targetQueryWrapper = new QueryWrapper<LCourseTarget>();
                targetQueryWrapper.eq("course_id",lCours.getCourseId());
                LCourseTarget lCourseTarget = ilCourseTargetService.getOne(targetQueryWrapper);
                if(null != lCourseTarget)
                    lCours.setlCourseTarget(lCourseTarget);
            }
            // 返回
            return new PageResult(lCourses.getTotal(), lCourses, ResultEnum.SUCCESS);
        }catch (Exception e){
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }


    //新增
    @ApiOperation(value = "添加")
    @PostMapping("/add")
    @UserLoginToken
    @Log(title = "添加课程", businessType = BusinessType.INSERT, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> add(@RequestBody LCourse lCourse, HttpServletRequest request){
        // token
        String token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if(lCourse!=null) {
                if (StringUtils.isEmpty(lCourse.getCourseName())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_COURSE_NAME);
                }
                if (StringUtils.isEmpty(lCourse.getCourseType())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_COURSE_TYPE);
                }
                if (StringUtils.isEmpty(lCourse.getCourseSortId())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_COURSE_SORT);
                }
                if (StringUtils.isEmpty(lCourse.getCourseCompany())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_COURSE_COMP);
                }
                if (StringUtils.isEmpty(lCourse.getCourseTheme())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_COURSE_THEME);
                }
                if (StringUtils.isEmpty(lCourse.getCourseFailTime())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_COURSE_FAIL_TIME);
                }
                if (StringUtils.isEmpty(lCourse.getCourseCover())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_COURSE_COVER);
                }
                if (StringUtils.isEmpty(lCourse.getRecommendStutes())) {
                    lCourse.setRecommendStutes("2");
                }
                if (StringUtils.isEmpty(lCourse.getReleaseStutes())) {
                    lCourse.setReleaseStutes("0");
                }
                if (StringUtils.isEmpty(lCourse.getReleaseTime())) {
                    lCourse.setReleaseTime(new Date());
                }
                if (StringUtils.isEmpty(lCourse.getClassHours())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_COURSE_CLASS_HOURS);
                }
                if (StringUtils.isEmpty(lCourse.getTeacher())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_COURSEWARE_TEACHER);
                }
                lCourse.setPeople(0);
                lCourse.setCreateTime(new Date());
                lCourse.setCreateUser(userId);
                if (iLCourseService.save(lCourse)) {
                    //课程类型1自选 2专题
                    if("2".equals(lCourse.getCourseType())){
                        // 新增发布对象
                        LCourseTarget lCourseTarget = lCourse.getlCourseTarget();
                        lCourseTarget.setCourseId(lCourse.getCourseId());
                        ilCourseTargetService.save(lCourseTarget);
                    }
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lCourse);
                }
            }
        }catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return  (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }


    //删除
    @ApiOperation(value = "删除")
    @PostMapping("/del")
    @UserLoginToken
    @Log(title = "删除课程", businessType = BusinessType.DELETE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> del(@RequestBody LCourse lCourse){
        try {
            if(lCourse!=null){
                if(lCourse.getCourseId()!=null) {
                    if(iLCourseService.removeById(lCourse.getCourseId()))
                        return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
                }
            }
        }catch (Exception e)
        {
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    //更新
    @ApiOperation(value = "更新")
    @PostMapping("/edit")
    @UserLoginToken
    @Log(title = "更新课程", businessType = BusinessType.UPDATE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> edit(@RequestBody LCourse lCourse, HttpServletRequest request) {
        if(lCourse!=null){
            // token
            String token = request.getHeader("token");
            String userId = JwtUtil.getUserId(token);
            lCourse.setUpdateTime(new Date());
            lCourse.setUpdateUser(userId);
            if(iLCourseService.updateById(lCourse)){
                //课程类型1自选 2专题
                if("2".equals(lCourse.getCourseType())){
                    // 新发布对象
                    LCourseTarget lCourseTarget = lCourse.getlCourseTarget();
                    if(null != lCourseTarget){
                        if(StringUtils.isNotEmpty(lCourseTarget.getCourseTargetId())){
                            ilCourseTargetService.updateById(lCourseTarget);
                        }else{
                            // 新增发布对象
                            lCourseTarget.setCourseId(lCourse.getCourseId());
                            ilCourseTargetService.save(lCourseTarget);
                        }
                    }
                }
                return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
            }
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }
}

